package org.jeecg.modules.front.util;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.front.cache.RedisCacheUtils;
import org.jeecg.modules.front.entity.resp.BusUserResp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Slf4j
@Component
public class UserLoginUtils {

    @Autowired
    private RedisCacheUtils redisCacheUtils;



    public Result<JsonObject> getUserInfo(BusUserResp userInfoResp, HttpServletRequest request) {
        JSONObject obj = new JSONObject();
        getUserLoginRespMsg(obj,userInfoResp,request);
        Result result = new Result();
        result.setResult(obj);
        result.setSuccess(true);
        result.setMessage("登录成功！");
        return result;
    }


    private JSONObject getUserLoginRespMsg(JSONObject object, BusUserResp userInfoResp, HttpServletRequest request){
        object.put("userInfo",userInfoResp);
        //生成用户token，并插入redis缓存
        String token = createRedisToken(request, userInfoResp.getUserId(),userInfoResp);
        object.put("token",token);
        log.info("---sessionId---:{}", request.getSession().getId());
        object.put("sessionId", request.getSession().getId());
        return object;
    }


    /**
     * 生成用户token，并插入redis缓存
     */
    private String createRedisToken(HttpServletRequest request, String userId, BusUserResp sysUserResp) {
        log.info("UserLoginUtils.createRedisToken：requestedsessionId={},sessionId={}",request.getRequestedSessionId(), request.getSession().getId());
        //清空session
        request.getSession().invalidate();
        log.info("UserLoginUtils.createRedisToken： invalidate after requestedsessionId={},sessionId={}", request.getRequestedSessionId(), request.getSession().getId());
        Cookie[] cookies = request.getCookies();
        if (Objects.nonNull(cookies) && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                log.info("cookie name={} value={}", cookie.getName(), cookie.getValue());
                cookie.setMaxAge(0);
            }
            log.info("UserLoginUtils.createRedisToken： requestedsessionId={},sessionId={}", request.getRequestedSessionId(), request.getSession().getId());

        }
        String token = JWTTokenUtil.getUserToken(userId, request.getSession().getId());
        //将登录返回对象存入session和redis中
        org.jeecg.modules.front.interceptor.UserContext.setSysUser(sysUserResp);
        log.info("<<<=================将登录返回对象存入session和redis中=================>>>{}", JSONObject.toJSONString(sysUserResp));
        redisCacheUtils.setSysUser(token, sysUserResp);
        redisCacheUtils.setIfAbsent(sysUserResp.getPhoneNum(), token);
        log.info("UserLoginUtils.createRedisToken：requestedsessionId={},sessionId={}", request.getRequestedSessionId(), request.getSession().getId());
        return token;
    }

}
